package cn.minhx.domain.trade.service.settlement.filter;

import cn.minhx.domain.trade.adapter.repostitory.ITradeRepository;
import cn.minhx.domain.trade.moedel.entity.GroupBuyTeamEntity;
import cn.minhx.domain.trade.moedel.entity.MarketPayOrderEntity;
import cn.minhx.domain.trade.moedel.entity.TradeSettlementRuleCommandEntity;
import cn.minhx.domain.trade.moedel.entity.TradeSettlementRuleFilterBackEntity;
import cn.minhx.domain.trade.service.settlement.factor.TradeSettlementRuleFilterFactory;
import cn.minhx.types.design.link.multi.handler.ILogicHandler;
import cn.minhx.types.enums.ResponseCode;
import cn.minhx.types.exception.AppException;
import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 可结算规则过滤；交易时间
 *
 * @author min
 */
@Slf4j
@Service
public class SettableRuleFilter
		implements
			ILogicHandler<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleFilterBackEntity> {

	@Resource
	private ITradeRepository repository;

	@Override
	public TradeSettlementRuleFilterBackEntity apply(TradeSettlementRuleCommandEntity requestParameter,
			TradeSettlementRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
		log.info("结算规则过滤-有效时间校验{} outTradeNo:{}", requestParameter.getUserId(), requestParameter.getOutTradeNo());
		// 上下文；获取数据
		MarketPayOrderEntity marketPayOrderEntity = dynamicContext.getMarketPayOrderEntity();
		// 查询拼团对象
		GroupBuyTeamEntity groupBuyTeamEntity = repository.queryGroupBuyTeamByTeamId(marketPayOrderEntity.getTeamId());
		// 外部交易时间 - 也就是用户支付完成的时间，这个时间要在拼团有效时间范围内
		LocalDateTime outTradeTime = requestParameter.getOutTradeTime();
		// 判断，外部交易时间，要小于拼团结束时间。否则抛异常。
		if (!outTradeTime.isBefore(groupBuyTeamEntity.getValidEndTime())) {
			log.error("订单交易时间不在拼团有效时间范围内");
			throw new AppException(ResponseCode.E0106);
		}
		// 设置上下文
		dynamicContext.setGroupBuyTeamEntity(groupBuyTeamEntity);
		return next(requestParameter, dynamicContext);
	}
}
